import {
    observable,
    action,
    runInAction,
    toJS,
} from 'mobx';
import axios from 'axios';

import globalStore from './global';

axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
// axios.defaults.headers.common['Cache-Control'] = 'no-cache';
// axios.defaults.headers.common['Pragma'] = 'no-cache';

export default class BaseStore {
    @observable static globalXHRCount = 0;
    @observable static isLogon = false;

    @action
    setVal(key, val) {
        if (!key) {
            return;
        }
        this[key] = val;
    }

    @action
    async request(options) {
        const {
            showGlobalLoading,
            verifyLogin,
            ...opts
        } = options;
        if (showGlobalLoading) {
            globalStore.globalXHRCount++;
        }
        let res;
        try {
            res = await axios(opts);
            res = res.data;
        } catch (err) {
            res = {
                code: '9999',
                message: '请求失败'
            }
        }
        if (showGlobalLoading || verifyLogin) {
            runInAction(() => {
                showGlobalLoading && globalStore.globalXHRCount--;
                if (res.code === '9000') {
                    globalStore.setVal('isLogon', false);
                    globalStore.setVal('err', '由于您长时间未操作，请重新登录');
                } else if (res.code === '9100') {
                    globalStore.setVal('isLogon', false);
                    globalStore.setVal('err', '企业信息已变更，请重新登录');
                } else if (res.code === '9101') {
                    globalStore.setVal('isLogon', false);
                    globalStore.setVal('err', '登录用户信息已变更，请重新登录');
                } else if (res.code === '9102') {
                    globalStore.setVal('isLogon', false);
                    globalStore.setVal('err', '登录用户已解除绑定，请重新登录');
                }
            });
        }
        return res;
    }

    async get(url, data, options = {}) {
        data = data || {};
        data._t = Date.now();
        options.method = 'get';
        options.url = url;
        options.params = data;
        return await this.request(options);
    }

    async post(url, data, options = {}) {
        options.method = 'post';
        options.url = url;
        options.data = data;
        return await this.request(options);
    }

    async put(url, data, options = {}) {
        options.method = 'put';
        options.url = url;
        options.data = data;
        return await this.request(options);
    }

    async delete(url, data, options = {}) {
        options.method = 'delete';
        options.url = url;
        options.params = data;
        return await this.request(options);
    }
}
